package my.util;

/**
 * <p>
 * 循环队列
 * </p>
 *
 * @author AJun
 * @since 2020/8/17
 */
@SuppressWarnings("ALL")
public class CircleQueue<E> {

    /**
     * 存储队头的下标
     */
    private int front;

    private int size;

    private E[] elements;

    private static final int DEFAULT_CAPACITY = 10;

    public CircleQueue() {
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean empty() {
        return size == 0;
    }

    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[index(i)] = null;
        }

        size = 0;
        front = 0;
    }

    public void enQueue(E element) {
        ensureCapacity(size + 1);

        elements[index(size)] = element;
        size++;
    }

    public E deQueue() {
        E frontElement = elements[front];
        elements[front] = null;
        front = index(1);
        size--;
        return frontElement;
    }

    public E front() {
        return elements[front];
    }

    /**
     * 映射真实索引
     */
    private int index(int index) {
        // return (front + index) % elements.length;

        // 取模优化
        index += front;
        return index - ((index >= elements.length) ? elements.length : 0);
    }


    /**
     * 动态扩容
     */
    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;

        // 新容量是旧的 1.5 倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }

        elements = newElements;
        front = 0; // front 重置为 0
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("capacity=").append(elements.length)
                .append(" size=").append(size)
                .append(" front=").append(front)
                .append(", [");
        for (int i = 0; i < elements.length; i++) {
            if (i != 0)
                string.append(", ");
            string.append(elements[i]);
        }
        string.append("]");
        return string.toString();
    }

}
